package com.myzl.web.controller.stream;

import com.myzl.coal.domain.Device;
import com.myzl.coal.service.IDeviceService;
import com.myzl.common.core.controller.BaseController;
import com.myzl.common.core.domain.AjaxResult;
import com.myzl.stream.pojo.ImageData;
import com.myzl.stream.service.IHIKSDKService;
import com.myzl.stream.service.IVideoConversionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 摄像头推流等功能
 * @date  2023年7月20日10:40:58
 * @author cew
 **/
@RestController
@RequestMapping("/stream")
public class CameraController extends BaseController {

	@Autowired
	private IHIKSDKService hikSDKService;

	@Autowired
	private IVideoConversionService videoConversionService;

	@Autowired
	private IDeviceService deviceService;

	/**
	 * 连接推流
	 */
	@GetMapping("/connect/{deviceId}")
	public AjaxResult connect(@PathVariable("deviceId") Integer deviceId)
	{
		Device device = deviceService.selectDeviceById(deviceId);
		ImageData imageData = buildImageData(device);
		String flvUrl = videoConversionService.live(imageData);
		return AjaxResult.success(flvUrl);
	}

	/**
	 * 连接保活
	 */
	@GetMapping("/keepLive/{deviceId}")
	public AjaxResult keepLive(@PathVariable("deviceId") Integer deviceId)
	{
		Device device = deviceService.selectDeviceById(deviceId);
		ImageData imageData = buildImageData(device);
		videoConversionService.keepLive(imageData);
		return AjaxResult.success();
	}

	/**
	 * 注销连接
	 */
	@GetMapping("/disConnect/{deviceId}")
	public AjaxResult disConnect(@PathVariable("deviceId") Integer deviceId)
	{
		Device device = deviceService.selectDeviceById(deviceId);
		ImageData imageData = buildImageData(device);
		videoConversionService.destroy(imageData);
		return AjaxResult.success();
	}

	/**
	 * 截取图片
	 */
	@PostMapping("/doSavePic")
	public AjaxResult doSavePic(@RequestBody ImageData imageData) {
		return hikSDKService.saveImage(imageData);
	}

	private ImageData buildImageData(Device device){
		ImageData imageData = new ImageData();
		imageData.setIp(device.getIp());
		imageData.setPort(device.getPort().shortValue());
		imageData.setUsername(device.getUserName());
		imageData.setPassword(device.getPassword());
		imageData.setChannel(device.getChannel());
		imageData.setDeviceId(device.getId());
		return imageData;
	}

}
